from flask import Blueprint, request, current_app, jsonify
from app.utils.mysql_db import get_db_connection, get_db_cursor, DatabaseLogger
from app.utils.logger import FlinkLogger, log_api_call, log_database_operation


bp = Blueprint("settings", __name__)

@bp.route('', methods=['GET'], endpoint='get_service_configs')
@log_api_call
def get_settings():
    """获取服务配置"""
    service_type = request.args.get('service_type')
    config_name = request.args.get('config_name')
    include_deleted = request.args.get('include_deleted', 'false').lower() == 'true'
    
    try:
        result = get_service_configs(service_type, config_name, include_deleted)
        return jsonify(result)
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500



def get_service_configs(service_type=None, config_name=None, include_deleted=False):
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            where_conditions = ["is_active = 1"]
            # 添加逻辑删除过滤条件
            if not include_deleted:
                where_conditions.append("is_deleted = 0")
            
            params = []
            if service_type:
                where_conditions.append("service_type = %s")
                params.append(service_type)
            if config_name:
                where_conditions.append("config_name = %s")
                params.append(config_name)
            where_clause = " AND ".join(where_conditions)
            order_clause = "ORDER BY service_type, sort_order, config_name"
            cur.execute(f"""
                SELECT id, service_type, config_name, host, port, username, password, `database`, 
                       protocol, path, extra_config, description, is_active, is_deleted, sort_order,
                       created_time, updated_time, deleted_time, created_by, updated_by, deleted_by
                FROM service_config 
                WHERE {where_clause}
                {order_clause}
            """, params)
            rows = cur.fetchall()
            configs = {}
            for row in rows:
                st = row['service_type']
                cn = row['config_name']
                if st not in configs:
                    configs[st] = {}
                base_config = {
                    'host': row['host'],
                    'port': row['port'],
                    'username': row['username'],
                    'password': row['password'],
                    'database': row['database'],
                    'protocol': row['protocol'] or 'http',
                    'path': row['path'],
                    'description': row['description'],
                    'sort_order': row['sort_order']
                }
                extra_config = {}
                if row['extra_config']:
                    try:
                        import json
                        extra_config = json.loads(row['extra_config'])
                    except Exception:
                        extra_config = {}
                configs[st][cn] = {**base_config, **extra_config}
            return configs
    finally:
        conn.close()


def save_service_config(service_type, config_name, configs, created_by='web_ui'):
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            # 先物理删除所有相同service_type和config_name的记录（包括已删除的）
            # 因为unique key包含is_deleted，不能有多条is_deleted=1的记录
            cur.execute("""
                DELETE FROM service_config 
                WHERE service_type = %s AND config_name = %s
            """, (service_type, config_name))
            
            base_fields = ['host','port','username','password','database','protocol','path','description','sort_order']
            extra_config = {k: v for k, v in configs.items() if k not in base_fields}
            host = configs.get('host', '')
            port = configs.get('port')
            username = configs.get('username', '')
            password = configs.get('password', '')
            database = configs.get('database', '')
            protocol = configs.get('protocol', 'http')
            path = configs.get('path', '')
            description = configs.get('description', '')
            sort_order = configs.get('sort_order', 0)
            import json
            extra_config_json = json.dumps(extra_config) if extra_config else None
            
            # 插入新配置
            cur.execute(
                """
                INSERT INTO service_config 
                (service_type, config_name, host, port, username, password, `database`, 
                 protocol, path, extra_config, description, is_active, is_deleted, sort_order, 
                 created_by, updated_by)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (service_type, config_name, host, port, username, password, database,
                 protocol, path, extra_config_json, description, 1, 0, sort_order, created_by, created_by)
            )
            conn.commit()
            return True
    except Exception as e:
        conn.rollback()
        return False, str(e)
    finally:
        conn.close()


@bp.get("")
@log_api_call("settings.list_configs")
def list_configs():
    current_app.logger.info("Listing service configurations")
    service_type = request.args.get('service_type')
    config_name = request.args.get('config_name')
    include_deleted = request.args.get('include_deleted', 'false').lower() == 'true'
    configs = get_service_configs(service_type, config_name, include_deleted)
    return {"configs": configs}


@bp.get("/deleted")
@log_api_call("settings.list_deleted_configs")
def list_deleted_configs():
    """获取已删除的配置（回收站）"""
    current_app.logger.info("Listing deleted service configurations")
    service_type = request.args.get('service_type')
    
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            where_conditions = ["is_deleted = 1"]
            params = []
            
            if service_type:
                where_conditions.append("service_type = %s")
                params.append(service_type)
            
            where_clause = " AND ".join(where_conditions)
            cur.execute(f"""
                SELECT id, service_type, config_name, host, port, username, password, `database`, 
                       protocol, path, extra_config, description, is_active, is_deleted, sort_order,
                       created_time, updated_time, deleted_time, created_by, updated_by, deleted_by
                FROM service_config 
                WHERE {where_clause}
                ORDER BY deleted_time DESC, service_type, config_name
            """, params)
            rows = cur.fetchall()
            
            # 格式化时间字段（避免时区转换问题）
            for row in rows:
                if row.get('created_time') and hasattr(row['created_time'], 'strftime'):
                    row['created_time'] = row['created_time'].strftime('%Y-%m-%d %H:%M:%S')
                if row.get('updated_time') and hasattr(row['updated_time'], 'strftime'):
                    row['updated_time'] = row['updated_time'].strftime('%Y-%m-%d %H:%M:%S')
                if row.get('deleted_time') and hasattr(row['deleted_time'], 'strftime'):
                    row['deleted_time'] = row['deleted_time'].strftime('%Y-%m-%d %H:%M:%S')
            
            configs = {}
            for row in rows:
                st = row['service_type']
                cn = row['config_name']
                if st not in configs:
                    configs[st] = {}
                configs[st][cn] = dict(row)
            
            return {"success": True, "message": "ok", "data": {"configs": configs}}
    finally:
        conn.close()


@bp.post("")
@log_api_call("settings.save_configs")
def save_configs():
    """保存环境配置列表"""
    current_app.logger.info("Saving environment configurations")
    data = request.get_json() or {}
    envs = data.get("environments") or []
    success_count = 0
    errors = []
    
    # 先逻辑删除所有现有的flink环境配置
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                UPDATE service_config 
                SET is_deleted = 1, deleted_time = CURRENT_TIMESTAMP, deleted_by = 'web_ui'
                WHERE service_type = 'flink' AND is_deleted = 0
            """)
            conn.commit()
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"清空现有配置失败: {str(e)}", "code": "SERVER_ERROR"}
    finally:
        conn.close()
    
    # 保存新的环境配置
    for i, env in enumerate(envs):
        name = (env.get('name') or '').strip()
        if not name:
            continue
            
        configs = {
            'host': env.get('host', ''),
            'port': int(env['port']) if str(env.get('port', '')).strip() else None,
            'protocol': env.get('protocol', 'http'),
            'path': env.get('path', '/'),
            'description': env.get('description') or f'Flink {name}环境',
            'sort_order': env.get('sort_order', i + 1),
        }
        
        ok = save_service_config('flink', name, configs)
        if ok is True:
            success_count += 1
        else:
            errors.append({"name": name, "error": ok[1] if isinstance(ok, tuple) else "unknown"})
    
    return {"success": True, "message": "ok", "data": {"saved": success_count, "errors": errors}}


@bp.post("/environment")
@log_api_call("settings.create_environment")
def create_environment():
    """创建单个服务配置"""
    current_app.logger.info("Creating new service environment")
    data = request.get_json() or {}
    name = (data.get('name') or '').strip()
    service_type = (data.get('service_type') or 'flink').strip()
    
    if not name:
        return {"success": False, "error": "配置名称不能为空", "code": "BAD_REQUEST"}, 400
    
    if not service_type:
        return {"success": False, "error": "服务类型不能为空", "code": "BAD_REQUEST"}, 400
    
    # 检查配置名称是否已存在
    existing_configs = get_service_configs(service_type, name)
    if existing_configs.get(service_type, {}).get(name):
        return {"success": False, "error": "配置名称已存在", "code": "CONFLICT"}, 400
    
    configs = {
        'host': data.get('host', ''),
        'port': int(data['port']) if str(data.get('port', '')).strip() else None,
        'protocol': data.get('protocol', 'http'),
        'path': data.get('path', '/'),
        'username': data.get('username', ''),
        'password': data.get('password', ''),
        'database': data.get('database', ''),
        'description': data.get('description') or f'{service_type.title()} {name}配置',
        'sort_order': data.get('sort_order', 0),
    }
    
    ok = save_service_config(service_type, name, configs)
    if ok is True:
        return {"success": True, "message": "服务配置创建成功", "name": name, "service_type": service_type}
    else:
        return {"success": False, "error": ok[1] if isinstance(ok, tuple) else "创建失败", "code": "SERVER_ERROR"}, 500


@bp.put("/environment/<service_type>/<config_name>")
@log_api_call("settings.update_environment")
def update_environment(service_type, config_name):
    """更新单个服务配置"""
    current_app.logger.info(f"Updating environment: {service_type}/{config_name}")
    data = request.get_json() or {}
    
    # 检查配置是否存在
    existing_configs = get_service_configs(service_type, config_name)
    if not existing_configs.get(service_type, {}).get(config_name):
        return {"success": False, "error": "服务配置不存在", "code": "NOT_FOUND"}, 404
    
    # 获取新的服务类型和配置名称
    new_service_type = data.get('service_type', service_type)
    new_config_name = data.get('name', config_name)
    
    # 如果服务类型或配置名称发生变化，需要检查新名称是否已存在
    if new_service_type != service_type or new_config_name != config_name:
        # 检查新名称是否已存在
        existing_new_configs = get_service_configs(new_service_type, new_config_name)
        if existing_new_configs.get(new_service_type, {}).get(new_config_name):
            return {"success": False, "error": "目标服务类型和配置名称已存在", "code": "CONFLICT"}, 400
    
    configs = {
        'host': data.get('host', ''),
        'port': int(data['port']) if str(data.get('port', '')).strip() else None,
        'protocol': data.get('protocol', 'http'),
        'path': data.get('path', '/'),
        'username': data.get('username', ''),
        'password': data.get('password', ''),
        'database': data.get('database', ''),
        'description': data.get('description') or f'{new_service_type.title()} {new_config_name}配置',
        'sort_order': data.get('sort_order', 0),
    }
    
    # 如果服务类型或配置名称发生变化，先删除旧记录，再创建新记录
    if new_service_type != service_type or new_config_name != config_name:
        conn = get_db_connection()
        try:
            with conn.cursor() as cur:
                # 删除旧记录
                cur.execute(
                    "DELETE FROM service_config WHERE service_type = %s AND config_name = %s",
                    (service_type, config_name)
                )
                conn.commit()
        except Exception as e:
            conn.rollback()
            return {"success": False, "error": f"删除旧配置失败: {str(e)}", "code": "SERVER_ERROR"}, 500
        finally:
            conn.close()
        
        # 创建新记录
        ok = save_service_config(new_service_type, new_config_name, configs)
        if ok is True:
            return {"success": True, "message": "服务配置更新成功", "name": new_config_name, "service_type": new_service_type}
        else:
            return {"success": False, "error": ok[1] if isinstance(ok, tuple) else "更新失败", "code": "SERVER_ERROR"}, 500
    else:
        # 只更新配置内容
        ok = save_service_config(service_type, config_name, configs)
        if ok is True:
            return {"success": True, "message": "服务配置更新成功", "name": config_name, "service_type": service_type}
        else:
            return {"success": False, "error": ok[1] if isinstance(ok, tuple) else "更新失败", "code": "SERVER_ERROR"}, 500


@bp.delete("/environment/<service_type>/<config_name>")
@log_api_call("settings.delete_environment")
def delete_environment(service_type, config_name):
    """逻辑删除单个服务配置"""
    current_app.logger.info(f"Soft deleting environment: {service_type}/{config_name}")
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            # 检查配置是否存在且未被删除
            cur.execute(
                "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 0",
                (service_type, config_name)
            )
            result = cur.fetchone()
            if result['count'] == 0:
                return {"success": False, "error": "服务配置不存在或已被删除", "code": "NOT_FOUND"}, 404
            
            # 逻辑删除配置
            cur.execute(
                """UPDATE service_config 
                   SET is_deleted = 1, deleted_time = CURRENT_TIMESTAMP, deleted_by = 'web_ui'
                   WHERE service_type = %s AND config_name = %s AND is_deleted = 0""",
                (service_type, config_name)
            )
            conn.commit()
            return {"success": True, "message": "服务配置删除成功", "name": config_name, "service_type": service_type}
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"删除失败: {str(e)}", "code": "SERVER_ERROR"}, 500
    finally:
        conn.close()


@bp.post("/environment/bulk-delete")
@log_api_call("settings.bulk_delete_environments")
def bulk_delete_environments():
    """批量删除服务配置"""
    current_app.logger.info("Bulk deleting service environments")
    data = request.get_json() or {}
    configs_to_delete = data.get('configs', [])
    
    if not configs_to_delete:
        return {"success": False, "error": "没有指定要删除的配置", "code": "BAD_REQUEST"}, 400
    
    conn = get_db_connection()
    success_count = 0
    failed_configs = []
    
    try:
        with conn.cursor() as cur:
            for config in configs_to_delete:
                service_type = config.get('service_type')
                config_name = config.get('name')
                
                if not service_type or not config_name:
                    failed_configs.append({
                        'service_type': service_type,
                        'name': config_name,
                        'error': '服务类型或配置名称为空'
                    })
                    continue
                
                try:
                    # 检查配置是否存在且未被删除
                    cur.execute(
                        "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 0",
                        (service_type, config_name)
                    )
                    result = cur.fetchone()
                    
                    if result['count'] == 0:
                        failed_configs.append({
                            'service_type': service_type,
                            'name': config_name,
                            'error': '配置不存在或已被删除'
                        })
                        continue
                    
                    # 逻辑删除配置
                    cur.execute(
                        """UPDATE service_config 
                           SET is_deleted = 1, deleted_time = CURRENT_TIMESTAMP, deleted_by = 'web_ui'
                           WHERE service_type = %s AND config_name = %s AND is_deleted = 0""",
                        (service_type, config_name)
                    )
                    success_count += 1
                    
                except Exception as e:
                    failed_configs.append({
                        'service_type': service_type,
                        'name': config_name,
                        'error': str(e)
                    })
            
            conn.commit()
            
        return {
            "success": True,
            "message": f"批量删除完成: 成功 {success_count} 个, 失败 {len(failed_configs)} 个",
            "data": {
                "success_count": success_count,
                "failed_count": len(failed_configs),
                "total_count": len(configs_to_delete),
                "failed_configs": failed_configs
            }
        }
        
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"批量删除失败: {str(e)}", "code": "SERVER_ERROR"}, 500
    finally:
        conn.close()


@bp.get("/environment/<service_type>/<config_name>")
@log_api_call("settings.get_environment")
def get_environment(service_type, config_name):
    """获取单个服务配置"""
    current_app.logger.info(f"Getting environment: {service_type}/{config_name}")
    configs = get_service_configs(service_type, config_name)
    env_config = configs.get(service_type, {}).get(config_name)
    
    if not env_config:
        return {"success": False, "error": "服务配置不存在", "code": "NOT_FOUND"}, 404
    
    return {
        "service_type": service_type,
        "name": config_name,
        "config": env_config
    }


@bp.post("/environment/<service_type>/<config_name>/restore")
@log_api_call("settings.restore_environment")
def restore_environment(service_type, config_name):
    """恢复已删除的服务配置"""
    current_app.logger.info(f"Restoring environment: {service_type}/{config_name}")
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            # 检查配置是否存在且已被删除
            cur.execute(
                "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 1",
                (service_type, config_name)
            )
            result = cur.fetchone()
            if result['count'] == 0:
                return {"success": False, "error": "服务配置不存在或未被删除", "code": "NOT_FOUND"}, 404
            
            # 检查是否有同名的活跃配置
            cur.execute(
                "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 0",
                (service_type, config_name)
            )
            result = cur.fetchone()
            if result['count'] > 0:
                return {"success": False, "error": "已存在同名的活跃配置，无法恢复", "code": "CONFLICT"}, 409
            
            # 恢复配置
            cur.execute(
                """UPDATE service_config 
                   SET is_deleted = 0, deleted_time = NULL, deleted_by = NULL, updated_by = 'web_ui'
                   WHERE service_type = %s AND config_name = %s AND is_deleted = 1""",
                (service_type, config_name)
            )
            conn.commit()
            return {"success": True, "message": "服务配置恢复成功", "name": config_name, "service_type": service_type}
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"恢复失败: {str(e)}", "code": "SERVER_ERROR"}, 500
    finally:
        conn.close()


@bp.delete("/environment/<service_type>/<config_name>/permanent")
@log_api_call("settings.permanent_delete_environment")
def permanent_delete_environment(service_type, config_name):
    """物理删除服务配置（永久删除）"""
    current_app.logger.info(f"Permanently deleting environment: {service_type}/{config_name}")
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            # 检查配置是否存在且已被删除
            cur.execute(
                "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 1",
                (service_type, config_name)
            )
            result = cur.fetchone()
            if result['count'] == 0:
                return {"success": False, "error": "服务配置不存在或未被删除", "code": "NOT_FOUND"}, 404
            
            # 物理删除配置
            cur.execute(
                "DELETE FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 1",
                (service_type, config_name)
            )
            conn.commit()
            return {"success": True, "message": "服务配置永久删除成功", "name": config_name, "service_type": service_type}
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"永久删除失败: {str(e)}", "code": "SERVER_ERROR"}, 500
    finally:
        conn.close()


@bp.post("/test-connection")
@log_api_call("settings.test_connection")
def test_connection():
    """测试服务连接"""
    current_app.logger.info("Testing service connection")
    data = request.get_json() or {}
    current_app.logger.info(f"收到的测试连接数据: {data}")
    service_type = data.get('service_type', '').lower()
    host = data.get('host', '')
    port = data.get('port')
    protocol = data.get('protocol', 'http')
    path = data.get('path', '/')
    username = data.get('username', '')
    password = data.get('password', '')
    database = data.get('database', '')
    
    current_app.logger.info(f"解析后 - host: {host}, port: {port}, service_type: {service_type}")
    
    if not host or not port:
        return {"success": False, "error": "主机和端口不能为空", "code": "BAD_REQUEST"}, 400
    
    try:
        import requests
        import socket
        from urllib.parse import urljoin
        
        # 根据服务类型进行不同的测试
        if service_type in ['flink', 'kafka']:
            # HTTP/HTTPS服务测试
            if protocol in ['http', 'https']:
                url = f"{protocol}://{host}:{port}{path}"
                response = requests.get(url, timeout=5)
                if response.status_code < 500:
                    return {"success": True, "message": f"连接成功 (HTTP {response.status_code})"}
                else:
                    return {"success": False, "error": f"服务返回错误: HTTP {response.status_code}", "code": "CONNECTION_ERROR"}, 400
            else:
                # TCP连接测试
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    sock.settimeout(5)
                    result = sock.connect_ex((host, int(port)))
                    if result == 0:
                        return {"success": True, "message": "TCP连接成功"}
                    else:
                        return {"success": False, "error": "TCP连接失败", "code": "CONNECTION_ERROR"}, 400
                finally:
                    sock.close()
        
        elif service_type in ['mysql', 'starrocks']:
            # MySQL/StarRocks连接测试
            import pymysql
            conn = None
            try:
                conn = pymysql.connect(
                    host=host,
                    port=int(port),
                    user=username,
                    password=password,
                    database=database if database else None,
                    connect_timeout=5
                )
                return {"success": True, "message": "数据库连接成功"}
            except pymysql.Error as e:
                return {"success": False, "error": f"数据库连接失败: {str(e)}", "code": "CONNECTION_ERROR"}, 400
            finally:
                if conn:
                    conn.close()
        
        elif service_type == 'redis':
            # Redis连接测试
            r = None
            try:
                import redis
                r = redis.Redis(
                    host=host,
                    port=int(port),
                    password=password if password else None,
                    socket_connect_timeout=5
                )
                r.ping()
                return {"success": True, "message": "Redis连接成功"}
            except Exception as e:
                return {"success": False, "error": f"Redis连接失败: {str(e)}", "code": "CONNECTION_ERROR"}, 400
            finally:
                if r:
                    try:
                        r.close()
                    except:
                        pass
        
        else:
            # 默认TCP测试
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                sock.settimeout(5)
                result = sock.connect_ex((host, int(port)))
                if result == 0:
                    return {"success": True, "message": "连接成功"}
                else:
                    return {"success": False, "error": "连接失败", "code": "CONNECTION_ERROR"}, 400
            finally:
                sock.close()
                
    except requests.exceptions.Timeout:
        return {"success": False, "error": "连接超时", "code": "TIMEOUT"}, 400
    except requests.exceptions.ConnectionError:
        return {"success": False, "error": "无法连接到服务", "code": "CONNECTION_ERROR"}, 400
    except Exception as e:
        current_app.logger.error(f"连接测试失败: {e}")
        return {"success": False, "error": f"连接测试失败: {str(e)}", "code": "SERVER_ERROR"}, 500


@bp.post("/environment/bulk-restore")
@log_api_call("settings.bulk_restore_environments")
def bulk_restore_environments():
    """批量恢复已删除的服务配置"""
    current_app.logger.info("Bulk restoring service environments")
    data = request.get_json() or {}
    configs_to_restore = data.get('configs', [])
    
    if not configs_to_restore:
        return {"success": False, "error": "没有指定要恢复的配置", "code": "BAD_REQUEST"}, 400
    
    conn = get_db_connection()
    success_count = 0
    failed_configs = []
    
    try:
        with conn.cursor() as cur:
            for config in configs_to_restore:
                service_type = config.get('service_type')
                config_name = config.get('name')
                
                if not service_type or not config_name:
                    failed_configs.append({
                        'service_type': service_type,
                        'name': config_name,
                        'error': '服务类型或配置名称为空'
                    })
                    continue
                
                try:
                    # 检查配置是否存在且已被删除
                    cur.execute(
                        "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 1",
                        (service_type, config_name)
                    )
                    result = cur.fetchone()
                    
                    if result['count'] == 0:
                        failed_configs.append({
                            'service_type': service_type,
                            'name': config_name,
                            'error': '配置不存在或未被删除'
                        })
                        continue
                    
                    # 检查是否有同名的活跃配置
                    cur.execute(
                        "SELECT COUNT(*) as count FROM service_config WHERE service_type = %s AND config_name = %s AND is_deleted = 0",
                        (service_type, config_name)
                    )
                    result = cur.fetchone()
                    if result['count'] > 0:
                        failed_configs.append({
                            'service_type': service_type,
                            'name': config_name,
                            'error': '已存在同名的活跃配置'
                        })
                        continue
                    
                    # 恢复配置
                    cur.execute(
                        """UPDATE service_config 
                           SET is_deleted = 0, deleted_time = NULL, deleted_by = NULL, updated_by = 'web_ui'
                           WHERE service_type = %s AND config_name = %s AND is_deleted = 1""",
                        (service_type, config_name)
                    )
                    success_count += 1
                    
                except Exception as e:
                    failed_configs.append({
                        'service_type': service_type,
                        'name': config_name,
                        'error': str(e)
                    })
            
            conn.commit()
            
        return {
            "success": True,
            "message": f"批量恢复完成: 成功 {success_count} 个, 失败 {len(failed_configs)} 个",
            "data": {
                "success_count": success_count,
                "failed_count": len(failed_configs),
                "total_count": len(configs_to_restore),
                "failed_configs": failed_configs
            }
        }
        
    except Exception as e:
        conn.rollback()
        return {"success": False, "error": f"批量恢复失败: {str(e)}", "code": "SERVER_ERROR"}, 500
    finally:
        conn.close()


